<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物料编辑</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f7f7f7; color: #333; }
        .admin-layout { background-color: #f7f7f7; }
        .content-wrapper { background-color: #fff; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 24px; margin: 20px; }
        .content-header { margin-bottom: 24px; border-bottom: 1px solid #f0f0f0; padding-bottom: 16px; }
        #pageTitle { font-size: 24px; font-weight: 600; color: #333; margin: 0; }
        .form-container { max-width: 600px; margin: 0 auto; }
        .form-group { margin-bottom: 20px; position: relative; }
        .form-label { font-size: 14px; font-weight: 500; color: #666; margin-bottom: 8px; display: block; }
        .required-field::after { content: "*"; color: #dc3545; margin-left: 4px; }
        .form-control, .form-select { height: 44px; border-radius: 10px; border: 1px solid #e0e0e0; padding: 0 16px; font-size: 16px; transition: all 0.2s ease; width: 100%; background-color: #f9f9f9; }
        .form-control:focus, .form-select:focus { border-color: #28a745; box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1); background-color: #fff; outline: none; }
        .btn { height: 44px; border-radius: 10px; font-size: 16px; font-weight: 500; padding: 0 20px; transition: all 0.2s ease; }
        .btn-primary { background-color: #28a745; border-color: #28a745; }
        .btn-primary:hover { background-color: #218838; border-color: #1e7e34; }
        .btn-secondary { background-color: #f2f2f7; border-color: #f2f2f7; color: #28a745; }
        .btn-secondary:hover { background-color: #e5e5ea; border-color: #e5e5ea; }
        .btn-action { min-width: 120px; }
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        @media (max-width: 768px) {
            .content-wrapper { padding: 16px; margin: 10px; }
            .form-container { padding: 0; }
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <!-- 顶部导航栏 -->
        <header class="admin-header">
            <div class="header-left">
                <div class="logo">生产过程管理系统</div>
            </div>
            <div class="header-right">
                <span class="user-info">管理员</span>
                <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
        </header>
        <!-- 左侧菜单 -->
        <aside class="admin-sidebar">
            <ul class="menu-list">
                <li class="menu-item">
                    <a href="../homepage/administrator_home.html">
                        <span class="menu-icon">🏠</span>
                        <span class="menu-title">首页</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">👥</span>
                        <span class="menu-title">人员管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../person/person_list.html">人员列表</a></li>
                        <li><a href="../person/person_edit.html">添加人员</a></li>
                    </ul>
                </li>
                <li class="menu-item active">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📦</span>
                        <span class="menu-title">物料管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="material_list.html">物料列表</a></li>
                        <li><a href="material_edit.html" class="active">添加物料</a></li>
                    </ul>
                </li>
              <li class="menu-item">
                <a href="javascript:void(0)">
                  <span class="menu-icon">⚙️</span>
                  <span class="menu-title">设备管理</span>
                  <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                  <li><a href="../device/device_list.html">设备列表</a></li>
                  <li><a href="../device/device_edit.html">添加设备</a></li>
                </ul>
              </li>
              <li class="menu-item">
                <a href="javascript:void(0)">
                  <span class="menu-icon">📝</span>
                  <span class="menu-title">产品管理</span>
                  <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                  <li><a href="../product/product_list.html">产品列表</a></li>
                  <li><a href="../product/product_edit.html">添加产品</a></li>
                </ul>
              </li>
              <li class="menu-item">
                <a href="javascript:void(0)">
                  <span class="menu-icon">🏢</span>
                  <span class="menu-title">供应商管理</span>
                  <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                  <li><a href="../provider/provider_list.html">供应商列表</a></li>
                  <li><a href="../provider/provider_edit.html">添加供应商</a></li>
                </ul>
              </li>
            </ul>
        </aside>
        <!-- 主内容区域 -->
        <main class="admin-main">
            <div class="content-wrapper">
                <div class="content-header">
                    <h2 id="pageTitle">添加物料</h2>
                </div>
                <div class="content-body">
                    <div class="form-container">
                        <form id="materialForm">
                            <input type="hidden" id="materialId">
                            <div class="form-group">
                                <label for="code" class="form-label">物料编号</label>
                                <input type="text" class="form-control" id="code" readonly disabled placeholder="物料编号将自动生成">
                                <small class="text-muted">物料编号将在保存后根据物料类型自动生成</small>
                            </div>
                            <div class="form-group">
                                <label for="name" class="form-label required-field">物料名称</label>
                                <input type="text" class="form-control" id="name" required>
                            </div>
                            <div class="form-group">
                                <label for="type" class="form-label required-field">材料类型</label>
                                <select class="form-select" id="type" required>
                                    <option value="">-- 请选择类型 --</option>
                                    <option value="金属">金属</option>
                                    <option value="合金">合金</option>
                                    <option value="复合材料">复合材料</option>
                                    <option value="其它">其它</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="providerName" class="form-label required-field">供应商名称</label>
                                <input type="text" class="form-control" id="providerName" required>
                            </div>
                            <div class="form-group">
                                <label for="factoryAddress" class="form-label">厂址</label>
                                <input type="text" class="form-control" id="factoryAddress">
                            </div>
                            <div class="form-group">
                                <label for="inboundDate" class="form-label required-field">入库时间</label>
                                <input type="date" class="form-control" id="inboundDate" required>
                            </div>
                            <div class="form-group">
                                <label for="spec" class="form-label">规格</label>
                                <input type="text" class="form-control" id="spec">
                            </div>
                            <div class="form-group">
                                <label for="contactPerson" class="form-label">联系人</label>
                                <input type="text" class="form-control" id="contactPerson">
                            </div>
                            <div class="form-group">
                                <label for="phone" class="form-label">手机</label>
                                <input type="text" class="form-control" id="phone">
                            </div>
                            <div class="form-group">
                                <label for="remark" class="form-label">物料说明</label>
                                <textarea class="form-control" id="remark" rows="3"></textarea>
                            </div>
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-secondary btn-action" onclick="goBack()">返回</button>
                                <button type="submit" class="btn btn-primary btn-action">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>
    <script src="../../assets/js/bootstrap.bundle.min.js"></script>
    <script>
        let isEditMode = false;
        let materialId = null;
        document.addEventListener('DOMContentLoaded', function () {
            var menuItems = document.querySelectorAll('.menu-item > a');
            menuItems.forEach(function (item) {
                item.addEventListener('click', function (e) {
                    var parent = item.parentElement;
                    document.querySelectorAll('.menu-item').forEach(function (el) {
                        if (el !== parent) el.classList.remove('active');
                    });
                    parent.classList.toggle('active');
                    e.preventDefault();
                });
            });
            // 添加首页链接的点击事件
            document.querySelector('.menu-item:first-child > a').addEventListener('click', function(e) {
                e.preventDefault(); // 阻止默认行为
                window.location.href = '../homepage/administrator_home.html'; // 跳转到管理员首页
            });
            // 默认展开物料管理菜单
            const materialMenuItem = document.querySelector('.menu-item:nth-child(3)');
            if (materialMenuItem) {
                materialMenuItem.classList.add('active');
            }
            // 设置当前页面对应的菜单项为选中状态
            const currentPath = window.location.pathname;
            const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
            document.querySelectorAll('.submenu li a').forEach(link => {
                if (link.getAttribute('href') === filename) {
                    link.classList.add('active');
                }
            });
            // 检查URL参数，判断是编辑还是新增
            const urlParams = new URLSearchParams(window.location.search);
            materialId = urlParams.get('id');
            if (materialId) {
                isEditMode = true;
                document.getElementById('pageTitle').textContent = '编辑物料';
                document.getElementById('materialId').value = materialId;
                loadMaterialData(materialId);
            } else {
                document.getElementById('pageTitle').textContent = '添加物料';
            }
            document.getElementById('materialForm').addEventListener('submit', function(e) {
                e.preventDefault();
                saveMaterial();
            });
        });

        async function loadMaterialData(id) {
            try {
                const response = await fetch(`http://localhost:8080/api/materials/${id}`);
                if (!response.ok) throw new Error('获取物料数据失败');
                const material = await response.json();
                document.getElementById('code').value = material.materialNumber || '';
                document.getElementById('name').value = material.name || '';
                document.getElementById('type').value = material.type || '';
                document.getElementById('providerName').value = material.providerName || '';
                document.getElementById('factoryAddress').value = material.providerAddress || '';
                document.getElementById('inboundDate').value = material.entryDate || '';
                document.getElementById('spec').value = material.specification || '';
                document.getElementById('contactPerson').value = material.contactPerson || '';
                document.getElementById('phone').value = material.phone || '';
                document.getElementById('remark').value = material.description || '';
            } catch (error) {
                console.error('加载物料数据失败:', error);
                alert('加载物料数据失败，请稍后重试');
            }
        }

        async function saveMaterial() {
            const form = document.getElementById('materialForm');
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }
            const materialData = {
                materialNumber: document.getElementById('code').value,
                name: document.getElementById('name').value,
                type: document.getElementById('type').value,
                providerName: document.getElementById('providerName').value,
                providerAddress: document.getElementById('factoryAddress').value,
                storageDate: document.getElementById('inboundDate').value,
                specification: document.getElementById('spec').value,
                contactPerson: document.getElementById('contactPerson').value,
                contactPhone: document.getElementById('phone').value,
                description: document.getElementById('remark').value
            };
            try {
                let url = 'http://localhost:8080/api/materials';
                let method = 'POST';
                if (isEditMode && materialId) {
                    url = `${url}/${materialId}`;
                    method = 'PUT';
                    materialData.id = parseInt(materialId);
                }
                const response = await fetch(url, {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(materialData)
                });
                if (!response.ok) throw new Error('保存物料数据失败');
                const result = await response.json();
                alert(result.message || '保存成功');
                window.location.href = 'material_list.html';
            } catch (error) {
                console.error('保存物料数据失败:', error);
                alert('保存物料数据失败，请稍后重试');
            }
        }
        function goBack() {
            window.location.href = 'material_list.html';
        }
        function logout() {
    // 添加确认提示
    if (confirm('确定要退出登录吗？')) {
        // 清除本地存储的登录信息
        localStorage.removeItem('userInfo');
        localStorage.removeItem('token');
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    }
}
    </script>
</body>
</html>